package com.example.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.bean.Category;
import com.example.reggie.bean.Dish;
import com.example.reggie.bean.Setmeal;
import com.example.reggie.service.CategoryService;
import com.example.reggie.service.DishService;
import com.example.reggie.service.SetmealService;
import com.example.reggie.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @GetMapping("/list")
    public R<ArrayList<Category>> allList(){
        LambdaQueryWrapper<Category> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        ArrayList<Category> arrayList=(ArrayList<Category>) categoryService.list(lambdaQueryWrapper);
        return R.success(arrayList);
    }
    @GetMapping("/page")
    public R<Page> list(int page,int pageSize){
        Page<Category> pageObj=new Page<>();
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageObj,queryWrapper);
        return R.success(pageObj);
    }
    @PostMapping
    public R<String> add(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加分类成功");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改分类成功");
    }

    @DeleteMapping
    @Transactional
    public R<String> delete(Long ids){
        //查询菜单查看是否存在该分类
        LambdaQueryWrapper<Dish> dishWrapper=new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getCategoryId,ids);
        int dishCount=dishService.count(dishWrapper);
        if (dishCount>0){
            throw new RuntimeException("菜单中存在该分类");
        }
        //查询套餐是否存在该分类
        LambdaQueryWrapper<Setmeal> setmealWrapper=new LambdaQueryWrapper<>();
        setmealWrapper.eq(Setmeal::getCategoryId,ids);
        int setmealCount=setmealService.count(setmealWrapper);
        if (setmealCount>0){
            throw new RuntimeException("套餐中存在该分类");
        }

        categoryService.removeById(ids);
        return R.success("删除分类成功");
    }
}
